import { createRouter, createWebHashHistory } from "vue-router";
// 导入utils工具
import { localGet } from "../../utils";

const router = createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory，history模式：createWebHistory
  routes: [
    {
      path: "/",
      redirect: "/login",
    },
    {
      path: "/home",
      name: "home",
      component: () => import("../views/Home.vue"),
      children: [
        {
          path: "dashboard", // 1. 子组件的path为空，默认渲染该子组件
          name: "dashboard",
          component: () => import("../views/Dashboard.vue"),
        },
        {
          path: "product",
          name: "product",
          component: () => import("../views/Product.vue"),
        },
        {
          path: "banner",
          name: "banner",
          component: () => import("../views/Banner.vue"),
        },
        {
          path: "users",
          name: "users",
          component: () => import("../views/Users.vue"),
        },
        {
          path: "goods",
          name: "goods",
          component: () => import("../views/Goods.vue"),
        },
        {
          path: "parts",
          name: "parts",
          component: () => import("../views/Parts.vue"),
        }
      ],
      redirect: "/home/dashboard", // 2. 通过redirect重定向，默认渲染该子组件
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/Login.vue"),
    }
  ],
});

// 路由全局守卫
router.beforeEach((to, from, next) => {
  if (to.path == "/login") {
    // 如果路径是 /login 则正常执行
    next();
  } else {
    // 如果不是 /login，判断是否有 token
    if (!localGet("token")) {
      // 如果没有，则跳至登录页面
      // next({ path: "/login" });
      next();
    } else {
      // 否则继续执行
      next();
    }
  }
});

export default router;
